package com.big.common.utils;
import ch.qos.logback.classic.gaffer.GafferConfigurator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.big.model.model.map.Coordinate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 获取经纬度
 *
 * @author jueyue 返回格式：Map<String,Object> map map.put("status",
 * reader.nextString());//状态 map.put("result", list);//查询结果
 * list<map<String,String>>
 * 密钥:f247cdb592eb43ebac6ccd27f796e2d2
 */
public class GetLatAndLngByBaidu {

    /**
     * @param addr
     * 查询的地址
     * @return
     * @throws IOException
     */
    public Object[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "f4ad4b6c46137f51a06f7195b0402d95";
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                System.out.println(br);
                String data = null;
                int count = 1;
                while((data= br.readLine())!=null){
                    if(count==5){
                        lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                        count++;
                    }else if(count==6){
                        lat = data.substring(data.indexOf(":")+1);//纬度
                        count++;
                    }else{
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return new Object[]{lng,lat};
    }
    /**
     * 徐州
     * 117.290575
     * 34.212667
     */

    /**
     * 成都
     * 104.072747
     * 30.578994
     */
    /**
     * 南京
     * 118.802422
     * 32.064653
     */
    public static void httpRequest() throws IOException {
        //得到long类型当前时间
        long l = System.currentTimeMillis();
        //调用的api的接口地址
        String apiPath = "https://restapi.amap.com/v3/direction/driving?origin=117.290575,34.212667&destination=118.802422,32.064653&extensions=all&output=json&key=f4ad4b6c46137f51a06f7195b0402d95";
        BufferedReader in = null;
        StringBuffer result = null;
        try {
            URL url = new URL(apiPath);
            //打开和url之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            connection.connect();
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            String result2 =  result.toString(); //返回json字符串
            //获取数据
            JSONObject jsonObject = JSON.parseObject(result2);
            String data = jsonObject.getString("route");

            JSONObject jsonObject2 = JSON.parseObject(data);
            String paths = jsonObject2.getString("paths");

            JSONArray objects = JSON.parseArray(paths);
            String steps=null;
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObjectlist = objects.getJSONObject(i);
                steps= jsonObjectlist.getString("steps");
            }
            List<Coordinate> coordinates = JsonUtils.jsonToList(steps, Coordinate.class);
            List<String>dae=new ArrayList<>();
            List<double[]>doubles=new ArrayList<>();
            coordinates.forEach(item->{
                String[] split = item.getPolyline().split(";");
                for (int i = 0; i < split.length; i++) {
                    dae.add((split[i]));
                }

            });
            dae.forEach(item -> {
                String[] split = item.split(",");
                for (int i = 0; i < split.length; i++){
                    double[] doub =new double[split.length];

                    if(i%2==0){
//                    System.out.println("经度"+split[i]);
                        doub[0] = Double.valueOf(split[i]);
                    }
                    if(i%1==0){
//                    System.out.println("纬度"+split[i]);
                        doub[1] = Double.valueOf(split[i]);
                    }
                    if(doub.length==2){
                        doubles.add(doub);
                    }
                }
            });
            for (int i = 0; i < doubles.size(); i++) {
                double[] doubles1 = doubles.get(i);
                if(i%2==0){
                    System.out.println("经度"+doubles1[0]);
                }
                if(i%1==0){
                    System.out.println("纬度"+doubles1[1]);
                }
            }
            System.out.println(doubles.size());
        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

    public static void main(String[] args) throws IOException {
        /**
         * 徐州
         * 117.290575
         * 34.212667
         */

//         httpRequest();
        /**
         * 成都
         * 104.072747
         * 30.578994
         */
        /**
         * 南京
         * 118.802422
         * 32.064653
         */
        GetLatAndLngByBaidu getLatAndLngByBaidu = new GetLatAndLngByBaidu();
        Object[] o = getLatAndLngByBaidu.getCoordinate("南京市鼓楼区阅江楼景区");
        System.out.println(o[0]);//经度
        System.out.println(o[1]);//纬度
//        double xzJ=117.290575;
//        double cdJ=104.072747;
//
//        double j =xzJ>cdJ ? xzJ: cdJ; //最大城市经度
//        System.out.println(j);


    }

}
